package com.dzsw.zk.demo;

import org.apache.zookeeper.*;

import java.util.List;
import java.util.concurrent.CountDownLatch;

public class ZkDemo1 {

    private ZooKeeper zk;

    private String ipAndPort;

    private int timeout;

    public ZkDemo1(String ipAndPort, int timeout) {
        this.ipAndPort = ipAndPort;
        this.timeout = timeout;
    }

    public void init() {
        try {
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            //连接成功后，会回调watcher监听，此连接操作是异步的，执行完new语句后，直接调用后续代码
            //  可指定多台服务地址 127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183
            String connectString = "192.168.85.191:2181";
            int timeout = 4000;
            zk = new ZooKeeper(connectString, timeout, event -> {
                if (Watcher.Event.KeeperState.SyncConnected == event.getState()) {
                    //如果收到了服务端的响应事件,连接成功
                    countDownLatch.countDown();
                }
            });
            countDownLatch.await();
            System.out.println(String.format("【初始化ZooKeeper连接状态....】=%s", zk.getState()));
        } catch (Exception e) {
            System.out.println(String.format("【初始化ZooKeeper连接异常....】=%s", e));
        }
    }

    /**
     *
     * @param path
     * @param value
     * @return 1=正常创建 2=节点已存在 3=其他异常无法创建
     */
    public int createNode(String path, String value) {
        int result = 3;
        try {
            zk.create(path, value.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            result = 1;
        } catch (KeeperException.NodeExistsException e) {
            result = 2;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (KeeperException e) {
            e.printStackTrace();
        }
        return result;
    }

    public void test() throws Exception {
        int childPath, result;
        do {
            List<String> nodePathList = zk.getChildren("/wns", false);
            nodePathList.sort((o1, o2) -> Integer.parseInt(o1) - Integer.valueOf(o2));
            int i = 0;
            boolean findBreak = false;
            for (String nodePath : nodePathList) {
                if (Integer.parseInt(nodePath) > i) {
                    findBreak = true;
                    break;
                }
                i++;
            }
            childPath = findBreak ? i : i + 1;
            result = createNode("/wns/" + childPath, "192.168.85.101");
        } while (result == 2);
    }

    public static void main(String[] args) throws Exception {
        String ipAndPort = "192.168.85.191:2181";
        int timeout = 4000;
        ZkDemo1 zkDemo1 = new ZkDemo1(ipAndPort, timeout);
        zkDemo1.init();
        for (int i = 0; i < 30; i++) {
            zkDemo1.test();
        }
        Thread.sleep(60 * 1000);
    }
}
